package com.alan.wifishare.presenter.wifi;

import java.util.ArrayList;
import java.util.List;

/**
 * AbsObserverManager 观察者管理器，负责向订阅该主题的观察者分发消息
 * @author JajuanWang
 * @date 2015-09-09 14:20
 * @version V1.0
 */
public class AbsObserverManager<T> {
	
	/**
	 * 观察者列表
	 */
	protected List<T> observerList;
	
	public AbsObserverManager() {
		super();
		observerList = new ArrayList<>();
	}
	
	/**
	 * 注册观察者，订阅消息
	 * @param observer 推送消息观察者，如果已经存在则之前注册的会被替换
	 */
	public void registerObserver(T observer) {
		if (observer == null) {
			throw new IllegalArgumentException("the observer is null!");
		}
		synchronized (observerList) {
			if (observerList.contains(observer)) {
				throw new IllegalArgumentException("the observer has been already registered!");
			}
			observerList.add(observer);
		}
	}
	
	/**
	 * 取消订阅
	 * @param observer
	 */
	public void unregisterObserver(T observer) {
		if (observer == null) {
			throw new IllegalArgumentException("the observer is null!");
		}
		synchronized (observerList) {
			if (!observerList.contains(observer)) {
				throw new IllegalArgumentException("the observer was not registered!");
			}
			observerList.remove(observer);
		}
	}
	
	/**
	 * 取消所有订阅
	 */
	public void unregisterAll(){
		synchronized (observerList) {
			observerList.clear();
		}
	}
}
